//
//  WJFileActivityItemSource.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/28.
//

import UIKit

class WJFileActivityItemSource: NSObject, UIActivityItemSource {
    private let temporaryFileURL: URL
    private let originalFileURL: URL
    private var cleanupHandler: (() -> Void)?
    
    init(originalFileURL: URL, customFileName: String, cleanupHandler: (() -> Void)? = nil) {
        self.originalFileURL = originalFileURL
        self.cleanupHandler = cleanupHandler
        
        let fileExtension = originalFileURL.pathExtension
        let tempDirectory = FileManager.default.temporaryDirectory
        let newFileURL = tempDirectory
            .appendingPathComponent(customFileName)
            .appendingPathExtension(fileExtension)
        
        self.temporaryFileURL = newFileURL
        
        super.init()
        
        // 复制文件到临时位置
        setupTemporaryFile()
    }
    
    private func setupTemporaryFile() {
        do {
            if FileManager.default.fileExists(atPath: temporaryFileURL.path) {
                try FileManager.default.removeItem(at: temporaryFileURL)
            }
            try FileManager.default.copyItem(at: originalFileURL, to: temporaryFileURL)
            print("临时文件创建成功: \(temporaryFileURL.lastPathComponent)")
        } catch {
            print("临时文件创建失败: \(error)")
        }
    }
    
    // MARK: - UIActivityItemSource
    
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return temporaryFileURL
    }
    
    func activityViewController(_ activityViewController: UIActivityViewController,
                               itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
        return temporaryFileURL
    }
    
    func activityViewController(_ activityViewController: UIActivityViewController,
                               subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
        return temporaryFileURL.deletingPathExtension().lastPathComponent
    }
    
    @available(iOS 13.0, *)
    func activityViewController(_ activityViewController: UIActivityViewController,
                               dataTypeIdentifierForActivityType activityType: UIActivity.ActivityType?) -> String {
        return (try? temporaryFileURL.resourceValues(forKeys: [.typeIdentifierKey]).typeIdentifier) ?? "public.data"
    }
    
    // 清理临时文件
    func cleanup() {
        if FileManager.default.fileExists(atPath: temporaryFileURL.path) {
            do {
                try FileManager.default.removeItem(at: temporaryFileURL)
                print("临时文件已删除: \(temporaryFileURL.lastPathComponent)")
            } catch {
                print("临时文件删除失败: \(error)")
            }
        }
        cleanupHandler?()
    }
}
